<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="线索ID" prop="leadId">
        <el-input
          v-model="queryParams.leadId"
          placeholder="请输入线索ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="活动信息" prop="activityInfo">
        <el-input
          v-model="queryParams.activityInfo"
          placeholder="请输入活动信息"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="归属人" prop="owner">
        <el-input
          v-model="queryParams.owner"
          placeholder="请输入归属人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['lead:lead:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lead:lead:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lead:lead:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['lead:lead:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload
            class="upload-demo"
            action="http://localhost:8080/lead/lead/leadImport">
          <el-button type="primary">+批量添加</el-button>
        </el-upload>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="leadList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="线索ID" align="center" prop="leadId" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="渠道来源" align="center" prop="channelSource" />
      <el-table-column label="活动信息" align="center" prop="activityInfo" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归属人" align="center" prop="owner" />
      <el-table-column label="线索状态" align="center" prop="leadStatus" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['lead:lead:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['lead:lead:remove']">删除</el-button>
          <!-- 状态为“待分配”时显示“分配”按钮 -->
          <el-button
              v-if="scope.row.leadStatus === '待分配'"
              type="text"
              @click="handleAllocate(scope.row)"
          >分配</el-button>
          <!-- 状态为“跟进中”时显示“查看”按钮 -->
          <el-button
              v-else-if="scope.row.leadStatus === '跟进中' || '待跟进'"
              type="text"
              @click="handleView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分配弹窗 -->
    <el-dialog v-model="allocateDialogVisible1" title="分配线索">
      <el-form :model="allocateForm" label-width="120px">
        <!-- 部门下拉框 -->
        <el-form-item label="请选择部门">
          <el-select v-model="form.channelSource" placeholder="请输入部门">
            <el-option label="线上活动" value="线上活动" />
            <el-option label="推荐介绍" value="推荐介绍" />
          </el-select>
        </el-form-item>
        <!-- 人员下拉框 -->
        <el-form-item label="请选择归属人员">
          <el-select v-model="form.owner" placeholder="请输入归属人员">
            <el-option label="小明" value="小明" />
            <el-option label="张三" value="张三" />
            <el-option label="小菲" value="小菲" />
            <el-option label="大飞" value="大飞" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="allocateDialogVisible = false">返回</el-button>
          <el-button type="primary" @click="confirmAllocate">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配失败提示 -->
    <el-dialog v-model="allocateFailVisible" title="分配失败">
      <p>保有量达到上限，最多选择3条线索</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="allocateFailVisible = false">确定</el-button>
        </span>
      </template>
    </el-dialog>


    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改线索对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="leadRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="活动信息" prop="activityInfo">
          <el-input v-model="form.activityInfo" placeholder="请输入活动信息" />
        </el-form-item>
        <el-form-item label="归属人" prop="owner">
          <el-input v-model="form.owner" placeholder="请输入归属人" />
        </el-form-item>
        <el-form-item label="渠道来源">
          <el-select v-model="form.channelSource" placeholder="请输入渠道来源">
            <el-option label="线上活动" value="线上活动" />
            <el-option label="推荐介绍" value="推荐介绍" />
          </el-select>
        </el-form-item>
        <el-form-item label="线索状态">
          <el-select v-model="form.leadStatus" placeholder="请输入线索状态">
            <el-option label="待跟进" value="待跟进" />
            <el-option label="跟进中" value="待跟进" />
            <el-option label="待分配" value="待跟进" />
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="form.sex">
            <el-radio value="0">女</el-radio>
            <el-radio value="1">男</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Lead">
import { listLead, getLead, delLead, addLead, updateLead } from "@/api/lead/lead"
import {
  __esModule as userOptions,
  __esModule as deptOptions,
  __esModule as selectedLeads,
  __esModule as allocateDialogVisible
} from "vue-cropper/dist/vue-cropper.umd.js";

const { proxy } = getCurrentInstance()

const leadList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    leadId: null,
    phone: null,
    channelSource: null,
    activityInfo: null,
    createTime: null,
    owner: null,
    leadStatus: null
  },
  rules: {
    phone: [
      { required: true, message: "手机号不能为空", trigger: "blur" }
    ],
    channelSource: [
      { required: true, message: "渠道来源不能为空", trigger: "change" }
    ],
    activityInfo: [
      { required: true, message: "活动信息不能为空", trigger: "blur" }
    ],
    owner: [
      { required: true, message: "归属人不能为空", trigger: "blur" }
    ],
    leadStatus: [
      { required: true, message: "线索状态不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询线索列表 */
function getList() {
  loading.value = true
  listLead(queryParams.value).then(response => {
    leadList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    leadId: null,
    phone: null,
    channelSource: null,
    activityInfo: null,
    createTime: null,
    owner: null,
    leadStatus: null
  }
  proxy.resetForm("leadRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.leadId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加线索"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _leadId = row.leadId || ids.value
  getLead(_leadId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改线索"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["leadRef"].validate(valid => {
    if (valid) {
      if (form.value.leadId != null) {
        updateLead(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addLead(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _leadIds = row.leadId || ids.value
  proxy.$modal.confirm('是否确认删除线索编号为"' + _leadIds + '"的数据项？').then(function() {
    return delLead(_leadIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('lead/lead/export', {
    ...queryParams.value
  }, `lead_${new Date().getTime()}.xlsx`)
}
getList()


/** 分配相关方法 */
// 点击“分配”按钮
function handleAllocate(row) {
  selectedLeads.value = [row]  // 单条线索分配
  getAllocateOptions()  // 加载部门和人员下拉数据
  allocateDialogVisible.value = false
}

// 点击“查看”按钮
function handleView(row) {
  console.log('查看线索详情', row)
  // 可添加跳转详情页或弹窗逻辑
}

// 获取部门、人员下拉选项
function getAllocateOptions() {
  // 加载部门列表
  getAllocateDepts().then(response => {
    deptOptions.value = response.data || []
  })
  // 加载人员列表（可根据部门筛选，这里为全量）
  getAllocateUsers().then(response => {
    userOptions.value = response.data || []
  })
}

// 确认分配
function confirmAllocate() {
  // 校验选中数量（最多3条）
  if (selectedLeads.value.length > 3) {
    allocateFailVisible.value = true
    return
  }
  // 调用分配接口
  allocateLead({
    leadIds: selectedLeads.value.map(lead => lead.leadId),
    deptId: allocateForm.deptId,
    userId: allocateForm.userId,
  }).then(() => {
    proxy.$message.success('分配成功')
    allocateDialogVisible.value = false
    getList()  // 分配后刷新列表
  }).catch(err => {
    proxy.$message.error('分配失败：' + (err.message || '未知错误'))
  })
}

</script>
